﻿
package test {
	import extremefx.tools.StringUtils;		import extremefx.i18n.ICustomFormatter;
	import extremefx.i18n.IFormatProvider;
	import extremefx.i18n.IFormattable;
	import extremefx.i18n.XString;	
	/**
	 * @author Marcelo Volmaro
	 */
	public class AnyRadix implements ICustomFormatter, IFormatProvider {
		private const _RADIX_CODE:String = "RA";
		
		public function AnyRadix() {
		}

		public function format(pFormat:String, pArgs:Object, formatProvider:IFormatProvider):String {
			pFormat = StringUtils.trim(pFormat);
			
			if (pFormat == "" || !StringUtils.startsWith(pFormat, _RADIX_CODE )) {
            	if (pArgs is IFormattable){
					return IFormattable(pArgs).toString(pFormat, formatProvider);
                    
            	}  else {
                	return pArgs.toString();
            	}
        	}
        	
        	// The formatting is handled here.
        	var radix:uint, longToBeFormatted:Number;

			// Extract the radix from the format string.
			pFormat = pFormat.replace(_RADIX_CODE, "");
			
			radix = uint(parseInt(pFormat));
			if (isNaN(radix)) throw new ArgumentError(XString.format("The radix \"{0}\" is invalid.", pFormat ));
			
			// Verify that the radix is in the proper range.
			if( radix <2 || radix > 36 ) throw new ArgumentError(XString.format("The radix \"{0}\" is not in the range 2..36.", radix ));
			
			// Verify that the argument can be converted to a long integer.
			longToBeFormatted = parseFloat(String(pArgs));
			if (isNaN(longToBeFormatted)) throw new ArgumentError(XString.format("The argument \"{0}\" cannot be converted to a number value.", pArgs));
			
			var out:String = Math.abs(longToBeFormatted).toString(radix);
			
			// Add a minus sign if the argument is negative.
        	if( longToBeFormatted < 0 ) out = out+'-';
        	return out;
		}
		
		public function getFormat(pType:*):* {
			if (pType is ICustomFormatter) return this;
            return null;
		}
	}
}
